package com.newtouch.cq.common.web.advice;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.newtouch.cq.lang.em.BaseExceptionEnum;
import com.newtouch.cq.lang.exception.IMccExceptionInfo;
import com.newtouch.cq.lang.result.MccResult;
import com.newtouch.cq.lang.util.LogUtil;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class GlobalExceptionHandler {

    private Log log = LogFactory.get(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public MccResult exceptionHandler(Exception e) {
        if (e instanceof IMccExceptionInfo) {
            LogUtil.error(log,(IMccExceptionInfo) e);
            return MccResult.fail((IMccExceptionInfo) e);
        } else if (StrUtil.contains(e.getClass().getName(),"AccessDeniedException") ) {
            LogUtil.error(log,BaseExceptionEnum.INSUFFICIENT_PERMISSIONS);
            return MccResult.fail(BaseExceptionEnum.INSUFFICIENT_PERMISSIONS);
        }
        log.error(e);
        return MccResult.fail(BaseExceptionEnum.ERROR);
    }
}
